<template>
    <div class="pictureManage">
        <div class="pictureManage-right">
            <div class="pictureManage-right-button">
                <div class="children-search">
                    <el-button size="small" @click="addFileFloor" icon="el-icon-plus">新建文件夹</el-button>
                    <el-button size="small" @click="uploadImg" type="primary" icon="el-icon-upload2">上传</el-button>
                    <el-button size="small" @click="delFile" icon="el-icon-delete">删除</el-button>
                    <el-button size="small" icon="el-icon-refresh" @click="getAllFile">刷新</el-button>
                </div>
                <div class="children-search">
                    <el-input v-model="searchInput" placeholder="请输入内容"></el-input>
                    <el-button size="small" type="primary" icon="el-icon-search" @click="searchList">搜索</el-button>
                </div>
            </div>
            <div style="width: 100%;height: 46px;display: flex;align-items: center;padding: 0 20px;box-sizing: border-box;">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item v-for="(items,index) in breadcrumbData">
                        <span @click="loadBreadcrumbDataData(items,index)">{{items.name}}</span>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="pictureManage-right-table">
                <el-table
                        v-loading="loading"
                        @selection-change="changeFun"
                        :data="fileTableData"
                        height="93%"
                        border
                        style="width: 100%;">
                    <el-table-column
                            align="center"
                            type="selection"
                            width="60">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="文件名">
                        <template slot-scope="scope">
                            <div @click.stop="lookFileFlooer(scope.row)"
                                 style="cursor: pointer;width: 100%;display: flex;justify-content: flex-start;align-items: center;">
                                <img v-if="scope.row.type==0" src="../../public/image/icon_wenjian.svg"/>
                                <img v-else-if="scope.row.type==1" src="../../public/image/icon_photo.svg"/>
                                <span style="margin-left: 15px;" v-text="scope.row.name"></span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="文件位置">
                        <template slot-scope="scope">
                            <span @click="openFileFloader(scope.row)" style="cursor: pointer;color: #66b1ff;"
                                  v-if="scope.row.type==1" v-text="scope.row.url"></span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            label="文件大小">
                        <template slot-scope="scope">
                            <span v-if="scope.row.type==1">{{scope.row.size | fileSizeZh}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            prop="createTime"
                            label="文件创建时间">
                    </el-table-column>
                    <el-table-column
                            align="center"
                            width="210"
                            label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    type="primary"
                                    size="mini"
                                    @click="handleRname(scope.$index, scope.row)">重命名
                            </el-button>
                            <el-button style="margin-left: 20px;"
                                    type="primary"
                                    size="mini"
                                    @click="handleMove(scope.$index, scope.row)">移动
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                        small
                        :current-page="page.pageNum"
                        :page-size="10"
                        :page-sizes="[10]"
                        layout="prev, pager, next, sizes"
                        @current-change="currentChange"
                        :total="total">
                </el-pagination>
            </div>
        </div>

        <!--新建文件夹-->
        <el-dialog title="新建文件夹" :visible.sync="addFileFloorVisible">
            <div>
                <el-input v-model="addInput" placeholder="请输入文件夹名称"></el-input>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="addFileFloorVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="primaryFileFloor">确 定</el-button>
            </div>
        </el-dialog>

        <!--重命名-->
        <el-dialog title="重命名" :visible.sync="againRnameVisible">
            <div>
                <el-input v-model="againRnameParams.name" placeholder="请输入重命名的名称"></el-input>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="againRnameVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="againRnameFileFloor">确 定</el-button>
            </div>
        </el-dialog>

        <!--图片预览-->
        <el-dialog title="图片预览" :visible.sync="imgYulan">
            <div style="display: flex;justify-content: center;width: 100%;">
                <img style="max-width: 100%;max-height: 300px;" :src="imgYulanUrl"/>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="imgYulan = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="imgYulan = false">确 定</el-button>
            </div>
        </el-dialog>

        <!--上传文件-->
        <el-dialog class="upload-box" @close="closeUpload" title="文件上传" :visible.sync="fileUploadVisible">
            <div>
                <el-upload
                        action="#"
                        ref="upload"
                        :multiple="true"
                        list-type="picture-card"
                        :auto-upload="false"
                        accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG"
                        :on-change="handleChange"
                        :on-exceed="onExceed"
                        :limit="$store.getters.getUploadNum">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                        >
                        <span class="el-upload-list__item-actions">
							 <span
                                     v-if="!disabled"
                                     class="el-upload-list__item-delete"
                                     @click="handleRemove(file)"
                             >
							  <i class="el-icon-delete"></i>
							</span>
                        </span>
                    </div>
                </el-upload>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="fileUploadVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="primaryImg">确 定</el-button>
            </div>
        </el-dialog>

        <!--弹出层-->
        <el-drawer
                title="移动目录"
                :append-to-body="true"
                custom-class="xzmltcc"
                :visible.sync="drawer"
                direction="rtl"
                :modal-append-to-body="false"
                :show-close="false"
                size="46%">
            <div class="mulucaidan">
                <el-tree ref="tree" node-key="id" :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                <el-button style="position: absolute;right: 20px;bottom:20px;" size="mini" type="primary" @click="moveTrue">移 动</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
    import {PicInfoService} from '@/util/sqlite/service/PicInfoService';
    import {MenuInfoService} from '@/util/sqlite/service/MenuInfoService';

    var fs = require('fs');

    /*文件*/
    var picInfoService = new PicInfoService();
    var serv = picInfoService.constructor.prototype;

    /*文件夹/菜单*/
    var menuInfoService = new MenuInfoService();
    var menuContrl = menuInfoService.constructor.prototype;

    export default {
        data() {
            return {
                //tree树
                drawer: true,
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'menu_name'
                },
                selectTreeId: "",
                //移动的是文件还是文件夹
                moveFileType: null,
                //移动文件的id
                moveFileId: null,

                //重命名
                againRnameVisible: false,
                againRnameParams: {},

                //图片预览
                imgYulan: false,
                imgYulanUrl: "",

                disabled: false,

                loading: true,
                multipleSelection: [],

                //总条数
                total: 0,
                page: {
                    pageSize: 5,
                    pageNum: 1
                },

                //表格文件
                fileTableData: [],

                //菜单id
                menuId: 0,//第一级为0

                tableData: [],//上传的图片数组
                searchInput: "",
                fileUploadVisible: false,

                //新增文件夹
                addFileFloorVisible: false,
                addInput: "",

                //面包屑
                breadcrumbData: [
                    {
                        name: "全部",
                        id: 0
                    }
                ]
            }
        },
        filters: {
            fileSizeZh(size) {
                var data = "";
                if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
                    data = size.toFixed(1) + "B";
                } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
                    data = (size / 1024).toFixed(1) + "KB";
                } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
                    data = (size / (1024 * 1024)).toFixed(1) + "MB";
                } else { //其他转化成GB
                    data = (size / (1024 * 1024 * 1024)).toFixed(1) + "GB";
                }
                var sizestr = data + "";
                var len = sizestr.indexOf("\.");
                var dec = sizestr.substr(len + 1, 2);
                if (dec == "00") {//当小数点后为00时 去掉小数部分
                    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
                }
                return sizestr;
            }
        },
        mounted() {
            let self = this;
            self.getAllFile();
        },
        methods: {
            handleMove(index,row){
                let self = this;
                self.drawer = true;
                self.moveFileType = row.type;
                self.moveFileId = row.id;
                self.getAllFileFloor(row);
            },
            //查询所有目录
            getAllFileFloor(row){
                let self = this;
                setTimeout(()=>{
                    let id = "";
                    if(row.type==1){
                        var obj = {
                        };
                        var res = serv.getAllMenu(obj);
                        if(res.code==200){
                            res.data.then((data)=>{
                                //得到分好级别的目录
                                self.getMenuTreeData(data);
                            });
                        }
                    }else {
                        id = row.id;
                        var res = serv.getMenuByNoParam(id);
                        res.then((data)=>{
                            //得到分好级别的目录
                            console.log("febnfefenfen",data);
                            self.getMenuTreeData(data);
                        });
                    }

                },300);
            },
            //先得到第一级目录
            getMenuTreeData (json_data) {
                var _this = this;
                var menuJsonData = [];// 菜单数组
                var parentList = [];// 所有一级菜单数组
                for (var i = 0; i < json_data.length; i++) {
                    var obj = {};
                    obj["children"] = [];//给每个菜单对象增加一个children属性
                    obj["id"] = json_data[i].id;
                    obj["parent_id"] = json_data[i].parent_id;
                    obj["menu_name"] = json_data[i].menu_name;
                    menuJsonData.push(obj);
                    if (json_data[i].parent_id == 0) {
                        parentList.push(obj);
                    }
                }
                for (var i = 0; i < parentList.length; i++) {
                    parentList[i] = _this.recuTree(parentList[i], menuJsonData);
                }

                _this.treeData = parentList;

                _this.treeData.unshift({
                    id: "",
                    menu_name: "根目录"
                })
            },
            recuTree (parentMenu, menuJsonData) {
                var _this = this;
                for (var i = 0; i < menuJsonData.length; i++) {
                    if (parentMenu.id == menuJsonData[i].parent_id) {
                        menuJsonData[i] = _this.recuTree(menuJsonData[i], menuJsonData);
                        parentMenu["children"].push(menuJsonData[i]);
                    }
                }

                return parentMenu;
            },

            //选中树
            handleNodeClick(data){
                let self = this;
                self.selectTreeId = data.id;
            },
            //确定移动
            moveTrue() {
                let self = this;
                if(self.selectTreeId==""){
                    self.$message({
                        type: 'warning',
                        message: '请选择移动的目录'
                    });
                    return;
                }
                if(self.moveFileType==1){
                    var obj = {
                        id: self.moveFileId,
                        picMneuId: self.selectTreeId
                    };
                    var res = serv.updatePicInfo(obj);
                    if (res.code == 200) {
                        self.page.pageNum = 1;
                        self.getAllFile();
                        self.drawer = true;
                    }
                }else{
                    var obj = {
                        id: self.moveFileId,
                        parentId: self.selectTreeId
                    };
                    var res = menuContrl.updateMenu(obj);
                    if (res.code == 200) {
                        self.page.pageNum = 1;
                        self.getAllFile();
                        self.drawer = true;
                    }
                }
            },

            //重命名
            //重命名输入弹框显示
            handleRname(index, row) {
                let self = this;
                self.againRnameParams = JSON.parse(JSON.stringify(row));
                self.againRnameVisible = true;
            },
            //重命名确认弹框
            againRnameFileFloor() {
                let self = this;
                if(self.againRnameParams.name==""){
                    self.$message({
                        type: 'warning',
                        message: '请输入重命名内容'
                    });
                    return;
                }
                let fileType = self.againRnameParams.type==1?'文件':'文件夹';
                self.$confirm('您确定要重命名此'+fileType+'么, 是否继续?', '提示', {
                    confirmButtonText: '确 定',
                    cancelButtonText: '取 消',
                    type: 'warning'
                }).then(() => {
                    if(self.againRnameParams.type==1){
                        var obj = {
                            id: self.againRnameParams.id,
                            picName: self.againRnameParams.name
                        };
                        var res = serv.updatePicInfo(obj);
                        if (res.code == 200) {
                            self.page.pageNum = 1;
                            self.getAllFile();
                            self.againRnameVisible = false;
                        }
                    }else{
                        var obj = {
                            id: self.againRnameParams.id,
                            menuName: self.againRnameParams.name
                        };
                        var res = menuContrl.updateMenu(obj);
                        if (res.code == 200) {
                            self.page.pageNum = 1;
                            self.getAllFile();
                            self.againRnameVisible = false;
                        }
                    }
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //查看图片
            openFileFloader(items) {
                let self = this;
                let dir = items.url;
                fs.exists(dir, function (bool) {
                    if (bool) {
                        const {shell} = require("electron").remote;
                        shell.showItemInFolder(dir);
                    } else {
                        self.$message({
                            message: "未找到项目文件!",
                            type: "warning",
                        })
                    }
                });
            },

            //搜索查询
            searchList() {
                let self = this;
                self.page.pageNum = 1;
                self.getAllFile();
            },

            //改变页码
            currentChange(value) {
                let self = this;
                self.page.pageNum = value;
                self.getAllFile();
            },

            //选中表格数据
            changeFun(val) {
                let self = this;
                self.multipleSelection = val;
            },

            //批量删除文件或者文件夹子
            delFile() {
                let self = this;
                if (self.multipleSelection.length <= 0) {
                    self.$message({
                        message: "请先选择要删除的文件/文件夹",
                        type: "warning"
                    });
                    return;
                }

                self.$confirm('此操作将永久删除该文件/文件夹, 是否继续?', '提示', {
                    confirmButtonText: '确 定',
                    cancelButtonText: '取 消',
                    type: 'warning'
                }).then(() => {
                    var res = null;
                    //删除图片
                    var res = serv.deletePicInfos(self.multipleSelection);
                    //删除菜单
                    var res1 = menuContrl.deleteMenuInfos(self.multipleSelection);

                    self.multipleSelection.forEach(async (items, index) => {
                        if (items.type == 1) {
                            await delFsFile(items.url);
                        }
                    });
                    self.page.pageNum = 1;
                    self.getAllFile();
                    self.$message({
                        type: 'success',
                        message: '删除成功!'
                    });

                    function delFsFile(url) {
                        return new Promise((reslove, reject) => {
                            fs.unlink(url, function (err) {
                                if (err) {
                                    reject();
                                    return;
                                }
                                reslove();
                            })
                        });
                    }
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //点击面包屑
            loadBreadcrumbDataData(items, index) {
                let self = this;
                if (items.id == self.menuId) {
                    return;
                }
                self.menuId = items.id;

                self.breadcrumbData.splice(index + 1, self.breadcrumbData.length + index + 1);

                self.page.pageNum = 1;
                self.getAllFile();
            },

            //查看某一级目录
            lookFileFlooer(row) {
                let self = this;
                if (row.type == 0) {
                    self.menuId = row.id;
                    self.breadcrumbData.push({
                        name: row.name,
                        id: row.id
                    });
                    self.page.pageNum = 1;
                    self.getAllFile();
                } else {
                    var fs = require("fs");
                    var imageData = fs.readFileSync(row.url);
                    var imageBase64 = imageData.toString("base64");
                    var imagePrefix = "data:image/bmp;base64,";

                    self.imgYulan = true;
                    self.$nextTick(() => {
                        self.imgYulanUrl = imagePrefix + imageBase64;
                    })
                }
            },

            //显示上传图片弹框
            uploadImg() {
                let self = this;
                if (self.$store.getters.getSaveCatalog == "") {
                    self.$message({
                        message: "请选择图片要存储的目录",
                        type: "warning"
                    });
                    return;
                }
                self.fileUploadVisible = true;
            },

            //删除上传的图片
            handleRemove(file, index) {
                let self = this;
                self.$refs.upload.handleRemove(file);
                let Index = 0;
                for (let i = 0; i < self.tableData.length; i++) {
                    let items = self.tableData[i];
                    if (items.picUrl == file.raw.path) {
                        Index = index;
                        break;
                    }
                }
                self.tableData.splice(index, 1);
            },

            //上传图片文件改变
            handleChange(file) {
                let self = this;
                let opt = {
                    picName: file.raw.name,
                    picUrl: file.raw.path,
                    picSize: file.raw.size,
                    picMneuId: self.menuId,
                    createTime: self.changeTime(new Date()),
                    catalog: self.$store.getters.getSaveCatalog
                };
                let flag = false;
                if (self.tableData.length > 0) {
                    for (let i = 0; i < self.tableData.length; i++) {
                        if (opt.picUrl === self.tableData[i].picUrl) {
                            flag = true;
                        }
                    }
                }
                if (flag) {
                    self.$message({
                        message: "请勿重新上传",
                        type: "warning"
                    });
                    self.$refs.upload.clearFiles();//调用element官方的方法
                    return;
                }
                self.tableData.push(opt);
            },

            //文件超出限制钩子函数
            onExceed(files, fileList) {
                let self = this;
                self.$message({
                    message: "文件最多上传" + self.$store.getters.getUploadNum + "张",
                    type: "warning"
                });
            },

            //上传图片弹框按钮确定事件
            primaryImg() {
                let self = this;
                self.addPicInfo();
            },

            //弹框关闭回调事件
            closeUpload() {
                let self = this;
                self.tableData = [];
                self.$nextTick(() => {
                    self.$refs.upload.clearFiles();//调用element官方的方法
                });
            },

            //确定上传逻辑
            addPicInfo() {
                //测试增加图片信息
                let self = this;
                let Index = 0;
                var isexist = fs.existsSync(self.$store.getters.getSaveCatalog);
                if (!isexist) {
                    self.$message({
                        message: "不存在文件存储目录，请更换系统目录",
                        type: "error"
                    });
                    return;
                }
                self.tableData.forEach((items, index) => {
                    fs.readFile(items.picUrl, function (err, data) {
                        if (err) {
                            throw err;
                        }
                        var index = items.picUrl.lastIndexOf("\\");
                        let str = items.picUrl.substring(index + 1, items.picUrl.length);
                        fs.writeFile(self.$store.getters.getSaveCatalog + "\\" + str, data, function (error) {
                            if (error) {
                                throw error;
                            }
                            Index++;
                            if (Index == self.tableData.length) {
                                self.tableData.forEach((IMGITEM, INDEX) => {
                                    var indexs = IMGITEM.picUrl.lastIndexOf("\\");
                                    let strs = IMGITEM.picUrl.substring(indexs + 1, IMGITEM.picUrl.length);
                                    IMGITEM.picUrl = self.$store.getters.getSaveCatalog + "\\" + strs;
                                });

                                var obj = self.tableData;
                                var res = serv.batchInsert(obj);
                                if (res.code === 200) {
                                    self.$message({
                                        message: "图片添加成功",
                                        type: "success"
                                    });
                                    self.fileUploadVisible = false;
                                    self.page.pageNum = 1;
                                    self.getAllFile();
                                } else {
                                    self.$message({
                                        message: "图片添加失败",
                                        type: "error"
                                    });
                                }
                            }
                        });
                    });
                });
            },

            //添加文件夹弹框显示
            addFileFloor() {
                let self = this;
                self.addFileFloorVisible = true;
            },

            //确认添加文件夹
            primaryFileFloor() {
                let self = this;
                if (self.addInput == "") {
                    self.$message({
                        message: "请输入文件夹名称",
                        type: "warning"
                    });
                    return;
                }
                var obj = {
                    menuName: self.addInput,
                    parentId: self.menuId,
                    createTime: self.changeTime(new Date())
                };
                var res = menuContrl.saveMenuInfo(obj);
                if (res.code === 200) {
                    self.$message({
                        message: "目录添加成功",
                        type: "success"
                    });
                    self.addFileFloorVisible = false;
                    self.addInput = "";

                    self.page.pageNum = 1;
                    self.getAllFile();
                } else {
                    self.$message({
                        message: "目录添加失败",
                        type: "error"
                    });
                }
            },

            //根据菜单id查询  菜单以及图片
            getAllFile() {
                let self = this;
                self.loading = true;
                setTimeout(() => {
                    var obj = {
                        id: self.menuId,
                        queryName: self.searchInput,
                        pageNum: self.page.pageNum,
                        pageSize: self.page.pageSize,
                        catalog: self.$store.getters.getSaveCatalog
                    };
                    var res = serv.getMenuAndPicByMenuId(obj);
                    if (res.code == 200) {
                        res.data.data.then((data) => {
                            self.fileTableData = data;
                        });

                        res.data.total.then((data) => {
                            self.total = data.length;
                        });
                    }
                    self.loading = false;
                }, 300);
            },

            //时间格式化
            changeTime(d) {
                let self = this;
                var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                return datetime;
            }
        }
    }
</script>

<style scoped lang="scss">
    /deep/ .el-breadcrumb__inner > span {
        cursor: pointer;
    }

    /deep/ .upload-box .el-dialog__body {
        max-height: 200px;
        overflow: auto;
    }

    /deep/ .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 150px;
        height: 150px;
    }

    /deep/ .upload-demo .el-upload--text {
        text-align: left !important;
    }

    /deep/ .avatar-uploader-icon {
        width: 150px !important;
        height: 150px !important;
        line-height: 150px !important;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .pictureManage {
        font-size: 18px;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        position: relative;
        width: 100%;
        height: 100%;
        overflow: hidden;
        padding: 20px 30px;
        background: #F4F4F4;
        box-sizing: border-box;

        .pictureManage-left {
            width: 260px;
            height: 100%;
            background: #F4F4F4;

            .pictureManage-left-title {
                width: 100%;
                font-size: 24px;
                font-family: "webfontM";
                box-sizing: border-box;
                padding: 20px;
            }
        }

        .pictureManage-right {
            position: relative;
            /*position: absolute;*/
            /*top: 0;*/
            /*left: 0px;*/
            /*right: 0;*/
            /*bottom: 0;*/
            width: 100%;
            height: 100%;
            background: #ffffff;
            border-radius: 8px;

            .pictureManage-right-button {
                width: 100%;
                height: 73px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #DCDFE6;
                box-sizing: border-box;

                button {
                    margin-left: 20px;
                }

                .children-search {
                    padding-right: 20px;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                }
            }

            .pictureManage-right-table {
                position: absolute;
                top: 100px;
                left: 0;
                right: 0;
                bottom: 0;
                overflow: hidden;
                padding: 20px;
            }
        }
    }
</style>
